<template>
  <div class="goods">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <el-card>
      <!-- 头部搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addGoods">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品展示 -->
      <el-table :data="goodsList" border stripe style="margin-top: 15px;">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" width="95px"></el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="70px"></el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="140px">
          <template v-slot="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editGoods(scope.row)"></el-button>

            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="deleteGoods(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页脚分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 3, 5, 15]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 编辑商品弹窗 -->
      <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <!-- 表单区域 -->
        <el-form :model="editGoodsForm" :rules="editGoodsRules" ref="editGoodsRef" label-width="100px">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="editGoodsForm.goods_name" disabled></el-input>
          </el-form-item>

          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model.number="editGoodsForm.goods_price" type="number"></el-input>
          </el-form-item>

          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model.number="editGoodsForm.goods_number" type="number"></el-input>
          </el-form-item>

          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model.number="editGoodsForm.goods_weight" type="number"></el-input>
          </el-form-item>

          <el-form-item label="商品介绍">
            <el-input v-model="editGoodsForm.goods_introduce" type="textarea"></el-input>
          </el-form-item>
        </el-form>

        <!-- 弹窗底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateGoods">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页数
        pagesize: 5 // 当前页面数据条数
      },
      goodsList: [],
      total: 0, // 商品总条数
      addDialogVisible: false, // 控制添加商品弹窗
      categoryList: [], // 商品分类数据
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      addGoodsForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { type: 'number', message: '重量必须为数字', trigger: 'blur' }
        ]
      },
      editGoodsRules: {
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { type: 'number', message: '重量必须为数字', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 控制编辑商品弹窗
      editGoodsForm: {
        goods_id: 0,
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: ''
      }
    }
  },
  filters: {
    dateFormat (timestamp) {
      const date = new Date(timestamp * 1000)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1 + '').padStart(2, '0')
      const day = (date.getDate() + '').padStart(2, '0')
      const hours = (date.getHours() + '').padStart(2, '0')
      const minutes = (date.getMinutes() + '').padStart(2, '0')
      const seconds = (date.getSeconds() + '').padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  },
  methods: {
    // 处理页面每张数据数量变化
    handleSizeChange (newVal) {
      this.queryInfo.pagesize = newVal
      this.getGoodsList()
    },

    // 处理页数变化
    handleCurrentChange (newVal) {
      this.queryInfo.pagenum = newVal
      this.getGoodsList()
    },

    async getGoodsList () {
      // 这里实现获取商品列表的逻辑
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
      this.goodsList = res.data.goods
      this.total = res.data.total
    },

    // 打开添加商品弹窗
    async addGoods () {
      this.$router.push('/goods/add')
    },

    // 关闭编辑商品弹窗时重置表单
    editDialogClosed () {
      this.$refs.editGoodsRef.resetFields()
    },

    // 编辑商品信息
    editGoods (row) {
      this.editGoodsForm.goods_id = row.goods_id
      this.editGoodsForm.goods_name = row.goods_name
      this.editGoodsForm.goods_price = row.goods_price
      this.editGoodsForm.goods_number = row.goods_number
      this.editGoodsForm.goods_weight = row.goods_weight
      this.editGoodsForm.goods_introduce = row.goods_introduce
      this.editDialogVisible = true
    },

    // 更新商品信息
    updateGoods () {
      this.$refs.editGoodsRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的商品信息')

        const form = {
          goods_name: this.editGoodsForm.goods_name,
          goods_price: this.editGoodsForm.goods_price,
          goods_number: this.editGoodsForm.goods_number,
          goods_weight: this.editGoodsForm.goods_weight,
          goods_introduce: this.editGoodsForm.goods_introduce,
          pics: this.editGoodsForm.pics,
          attrs: this.editGoodsForm.attrs
        }

        const { data: res } = await this.$http.put(`goods/${this.editGoodsForm.goods_id}`, form)
        if (res.meta.status !== 200) return this.$message.error('更新商品失败')

        this.$message.success('更新商品成功')
        this.editDialogVisible = false
        this.getGoodsList()
      })
    },

    // 删除商品
    deleteGoods (id) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`goods/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除商品失败')
        this.$message({
          type: 'success',
          message: '删除商品成功!'
        })
        this.getGoodsList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  created () {
    this.getGoodsList()
  }
}
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}
</style>
